package com.leruan.aasimp.dao.impl;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

import org.hibernate.Query;
import org.hibernate.Session;
import org.springframework.orm.hibernate3.support.HibernateDaoSupport;

import com.leruan.aasimp.constant.UsedCarConstant;
import com.leruan.aasimp.dao.MainPostDao;
import com.leruan.aasimp.entity.Mainpost;
import com.leruan.aasimp.entitydto.MainPostDto;
import com.leruan.aasimp.util.Validators;

public class MainPostDaoImpl extends HibernateDaoSupport implements MainPostDao {

    public List<Mainpost> findMainPostsByBoardId(String boardId) {
        Session session = this.getSession();
        String hql = "from Mainpost where boardId=?";
        return session.createQuery(hql).setString(0, boardId).list();
    }

    public Mainpost findMainPostsByPostId(String postId) {
        Session session = this.getSession();
        String hql = "from Mainpost where postId=?";
        return (Mainpost) session.createQuery(hql).setString(0, postId).uniqueResult();
    }

    public List<Mainpost> findMainPostsNewest() {
        Session session = this.getSession();
        String hql = "from Mainpost order by postDate desc,modifyDate desc";
        return session.createQuery(hql).list();
    }

    public List<Mainpost> findMainPostsPopular(Date dateStart, Date dateEnd) {
        Session session = this.getSession();
        String hql = "from Mainpost where postDate >= ? and postDate <= ? order by replyNum desc,hits desc";
        return session.createQuery(hql).setDate(0, dateStart).setDate(1, dateEnd).list();
    }

    public List<Mainpost> findMainPostsNewEssence() {
        Session session = this.getSession();
        String hql = "from Mainpost where type=1 order by postDate desc";
        return session.createQuery(hql).list();
    }

    public void updateMainPost(Mainpost mainpost) {
        getHibernateTemplate().update(mainpost);
    }

    public void insertMainPost(Mainpost mainpost) {
        Session session = this.getSession();
        session.save(mainpost);
    }

    public void showUpdate(String id) {
        System.out.println(id);
    }

    public void deleteMainPost(Mainpost mainpost) {
        Session session = this.getSession();
        String hql = "delete from Mainpost where postId=?";
        session.createQuery(hql).setString(0, mainpost.getPostId()).executeUpdate();
    }

    public List<MainPostDto> findMainPostsByBoardId(String boardId, Map<String, String> map, int pageNo) {
        Session session = this.getSession();
        StringBuffer sb = null;
        sb = new StringBuffer(
                "select m.id,m.postId,m.postTitle,m.userId,m.type,m.content,m.postDate,m.replyNum,m.hits,m.boardId,"
                        + "m.lastReplyUserId,m.lastReplyDate,m.score,m.modifyDate ,f.username,b.boardName from Mainpost m,Board b,Forumuser f where m.boardId=b.boardId"
                        + " and m.userId = f.userId and m.boardId=?");
        if (null != map) {
            if (!Validators.isEmpty(map.get("userId"))) {
                sb.append(" and m.userId='" + map.get("userId") + "'");
            }
            if (!Validators.isEmpty(map.get("postTitle"))) {
                sb.append(" and m.postTitle=like'%" + map.get("postTitle") + "%'");
            }
            if (map.get("postDateStart") != null && !"".equals(map.get("postDateStart"))) {
                sb.append(" and m.postDate > " + map.get("postDateStart"));
            }
            if (map.get("postDateEnd") != null && !"".equals(map.get("postDateEnd"))) {
                sb.append(" and m.postDate <" + map.get("postDateEnd"));
            }
        }
        sb.append(" order by m.postDate desc");
        Query query = session.createQuery(sb.toString());
        int first = (pageNo - 1) * UsedCarConstant.PAGE_SIZE;
        query.setString(0, boardId);
        query.setFirstResult(first);
        query.setMaxResults(UsedCarConstant.PAGE_SIZE);

        List list = query.list();
        List<MainPostDto> mainPostList = new ArrayList<MainPostDto>();
        for (int i = 0; i < list.size(); i++) {
            MainPostDto mainpost = new MainPostDto();
            Object[] object = (Object[]) list.get(i);
            mainpost.setId((Long) object[0]);
            mainpost.setPostId((String) object[1]);
            mainpost.setPostTitle((String) object[2]);
            mainpost.setUserId((String) object[3]);
            mainpost.setType((Long) object[4]);
            mainpost.setContent((String) object[5]);
            mainpost.setPostDate((Date) object[6]);
            mainpost.setReplyNum((Long) object[7]);
            mainpost.setHits((Long) object[8]);
            mainpost.setBoardId((String) object[9]);
            mainpost.setLastReplyUserId((String) object[10]);
            mainpost.setLastReplyDate((Date) object[11]);
            mainpost.setScore((Long) object[12]);
            mainpost.setModifyDate((Date) object[13]);
            mainpost.setUserName((String) object[14]);
            mainpost.setBoardName((String) object[15]);
            mainPostList.add(mainpost);
        }
        return mainPostList;
    }

    public Long findMainPostTotal(String boardId, Map<String, String> map) {
        Session session = this.getSession();
        StringBuffer sb = new StringBuffer("select count(id) from Mainpost where boardId=? and type not in(1,2)");
        if (null != map) {
            if (!Validators.isEmpty(map.get("userId"))) {
                sb.append(" and userId='" + map.get("userId") + "'");
            }
            if (!Validators.isEmpty(map.get("postTitle"))) {
                sb.append(" and postTitle=like'%" + map.get("postTitle") + "%'");
            }
            if (!Validators.isEmpty(map.get("postDateStart"))) {
                sb.append(" and postDate > " + map.get("postDateStart"));
            }
            if (!Validators.isEmpty(map.get("postDateEnd"))) {
                sb.append(" and postDate <" + map.get("postDateEnd"));
            }
        }
        return (Long) session.createQuery(sb.toString()).setString(0, boardId).uniqueResult();
    }

    public List<Mainpost> findMainPostsByUserId(String userId) {
        Session session = this.getSession();
        String hql = "from Mainpost where userId=?";
        return session.createQuery(hql).setString(0, userId).list();
    }

    public Long findMainPostNumById(String userId) {
        Session session = this.getSession();
        String hql = "select count(id) from Mainpost where userId=?";
        return (Long) session.createQuery(hql).setString(0, userId).uniqueResult();
    }

    public List<MainPostDto> findMainPostsByUserId(String userId, int pageNo) {
        Session session = this.getSession();
        StringBuffer sb = null;
        sb = new StringBuffer(
                "select m.id,m.postId,m.postTitle,m.userId,m.type,m.content,m.postDate,m.replyNum,m.hits,m.boardId,"
                        + "m.lastReplyUserId,m.lastReplyDate,m.score,m.modifyDate ,f.username,b.boardName from Mainpost m,Board b,Forumuser f where m.boardId=b.boardId"
                        + " and m.userId = f.userId and m.userId=?");
        sb.append(" order by m.postDate desc");
        Query query = session.createQuery(sb.toString());
        int first = (pageNo - 1) * UsedCarConstant.PAGE_SIZE;
        query.setString(0, userId);
        query.setFirstResult(first);
        query.setMaxResults(UsedCarConstant.PAGE_SIZE);

        List list = query.list();
        List<MainPostDto> mainPostList = new ArrayList<MainPostDto>();
        for (int i = 0; i < list.size(); i++) {
            MainPostDto mainpost = new MainPostDto();
            Object[] object = (Object[]) list.get(i);
            mainpost.setId((Long) object[0]);
            mainpost.setPostId((String) object[1]);
            mainpost.setPostTitle((String) object[2]);
            mainpost.setUserId((String) object[3]);
            mainpost.setType((Long) object[4]);
            mainpost.setContent((String) object[5]);
            mainpost.setPostDate((Date) object[6]);
            mainpost.setReplyNum((Long) object[7]);
            mainpost.setHits((Long) object[8]);
            mainpost.setBoardId((String) object[9]);
            mainpost.setLastReplyUserId((String) object[10]);
            mainpost.setLastReplyDate((Date) object[11]);
            mainpost.setScore((Long) object[12]);
            mainpost.setModifyDate((Date) object[13]);
            mainpost.setUserName((String) object[14]);
            mainpost.setBoardName((String) object[15]);
            mainPostList.add(mainpost);
        }
        return mainPostList;
    }
}
